package com.woniuxy.patrol.controller;

import cn.hutool.db.PageResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.common.utils.ResponseUtil;
import com.woniuxy.patrol.dto.UpdateTaskStatusDTO;
import com.woniuxy.patrol.mapper.PatrolTaskMapper;
import com.woniuxy.patrol.pojo.PatrolTask;
import com.woniuxy.patrol.service.PatrolTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
@RestController
@RequestMapping("/patrol/task")
public class PatrolTaskController {
    @Resource
    private PatrolTaskService taskService;
    @Resource
    private PatrolTaskMapper baseMapper;

    /**
     * 手动触发当日任务生成（测试用）
     */
    @GetMapping("/generate/daily")
    public ResponseUtil generateDailyTasks() {
        return taskService.generateDailyTasks();
    }

    /**
     * 更新任务状态
     */
    @PostMapping("/update/status")
    public ResponseUtil updateStatus(@RequestBody UpdateTaskStatusDTO dto) {
        Long taskId = dto.getTaskId();
        Integer status = dto.getStatus();
        String remark = dto.getRemark();
        // 校验任务ID有效性
        PatrolTask task = taskService.getById(taskId);
        if (task == null) {
            return ResponseUtil.error("任务不存在");
        }
        // 校验状态值合法性
        if (status < 0 || status > 5) {
            return ResponseUtil.error("无效的状态值");
        }
        return taskService.updateTaskStatus(taskId, status, remark);
    }
    /**
     * 新增：获取任务统计数据
     * 必须参数：统计日期（默认今日）、社区ID
     */
    @GetMapping("/get-stats")
    public ResponseUtil getTaskStats(
            @RequestParam(required = false) LocalDate date,
            @RequestParam(required = false) Long communityId) {
        return taskService.getTaskStats(date, communityId);
    }
// PatrolTaskController.java 的 getTaskStats 方法
//    @GetMapping("/get-stats")
//    public ResponseUtil getTaskStats(
//            @RequestParam(required = false) LocalDate date,
//            @RequestParam(required = false) Long communityId) {
//        try {
//            LocalDate statsDate = date == null ? LocalDate.now() : date;
//            // 替换条件：按 planned_start_time 的日期筛选，而非 task_date
//            LocalDateTime startOfDay = statsDate.atStartOfDay();
//            LocalDateTime endOfDay = statsDate.atTime(LocalTime.MAX);
//
//            QueryWrapper<PatrolTask> query = new QueryWrapper<>();
//            query.ge("planned_start_time", startOfDay)  // 计划开始时间 >= 今日 00:00:00
//                    .le("planned_start_time", endOfDay)    // 计划开始时间 <= 今日 23:59:59
//                    .eq("is_delete", 1);
//            if (communityId != null) {
//                query.eq("community_id", communityId);
//            }
//
//            long total = baseMapper.selectCount(query);
//            query.eq("task_status", 1);
//            long ongoing = baseMapper.selectCount(query);
//            query.eq("task_status", 2);
//            long completed = baseMapper.selectCount(query);
//            long unfinished = total - completed;
//
//            Map<String, Object> stats = new HashMap<>();
//            stats.put("total", total);
//            stats.put("ongoing", ongoing);
//            stats.put("completed", completed);
//            stats.put("unfinished", unfinished);
//
//            return ResponseUtil.success(stats);
//        } catch (Exception e) {
//            log.error("获取任务统计失败", e);
//            return ResponseUtil.error("获取任务统计失败");
//        }
//    }
    /**
     * 查询当日任务列表
     */
    @GetMapping("/today")
    public ResponseUtil getTodayTasks(
            @RequestParam(required = false) Long communityId,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) String keyword,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize
    ) {
        Map<String, Object> params = new HashMap<>();
        params.put("communityId", communityId);
        params.put("status", status);
        params.put("keyword", keyword);
        params.put("page", page);
        params.put("pageSize", pageSize);

        List<PatrolTask> tasks = taskService.getTodayTasks(params);
        long total = taskService.countTodayTasks(params);

        // 使用Map包装数据
        Map<String, Object> result = new HashMap<>();
        result.put("records", tasks);
        result.put("total", total);

        return ResponseUtil.success(result);
    }

    /**
     * 计算任务完成率
     */
    @GetMapping("/completion")
    public ResponseUtil calculateCompletion(@RequestParam Long taskId) {
        return taskService.calculateCompletionRate(taskId);
    }

    /**
     * 根据ID查询任务详情
     */
    @GetMapping("/{taskId}")
    public ResponseUtil getTaskDetail(@PathVariable Long taskId) {
        PatrolTask task = taskService.getById(taskId);
        // 修正判断逻辑：is_delete=0表示存在，=1表示已删除
        if (task == null || task.getIsDelete() == 0) {
            return ResponseUtil.error("任务不存在");
        }
        return ResponseUtil.success(task);
    }
    /**
     * 检查是否可以生成当日任务
     */
    @GetMapping("/can-generate-today")
    public ResponseUtil checkCanGenerateTodayTasks(
            @RequestParam Long communityId) {
        // 新增参数校验
        if (communityId == null || communityId <= 0) {
            return ResponseUtil.error("社区ID必须为正整数");
        }
        return taskService.checkCanGenerateTodayTasks(communityId);
    }
    /**
     * 查询逾期任务列表
     */
    @GetMapping("/overdue")
    public ResponseUtil getOverdueTasks(
            @RequestParam(required = false) Long communityId
    ) {
        Map<String, Object> params = new HashMap<>();
        params.put("communityId", communityId);
        params.put("status", 5); // 只查询状态为5（执行失败）的任务

        List<PatrolTask> tasks = taskService.getTodayTasks(params);
        long total = taskService.countTodayTasks(params);

        Map<String, Object> result = new HashMap<>();
        result.put("records", tasks);
        result.put("total", total);

        return ResponseUtil.success(result);
    }

    @GetMapping("/refresh-stats")
    public ResponseUtil refreshTaskStats(@RequestParam Long communityId) {
        // 触发逾期检查
        taskService.checkAndUpdateExpiredTasks();

        // 返回最新统计数据
        return taskService.getTaskStats(null, communityId);
    }
}
